'use strict';
module.exports = {
	/**
	 * 更新账本
	 * @url client/accountbook/kh/updateAccountBook 前端调用的url参数地址
	 * data 请求参数
	 * @params {String} accountBookName  账本名称
	 * @params {String} accountType  账本类型
	 * @params {String} remarks  账本说明
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, originalParam } = event;
		let { customUtil, config, pubFun, vk, db, _ } = util;
		let { uid,accountBook } = data && data;
		let res = { code : 0, msg : '更新成功' };
		// 业务逻辑开始-----------------------------------------------------------
		if(accountBook == null ){
			return { code : 1001, msg : '参数错误' };
		}
		
		let { accountBookName,accountType,remarks } = accountBook;
		if(accountBookName == null || accountBookName == "" || accountType == null || accountType == ""){
			return { code : 1001, msg : '参数错误' };
		}
		
		if (uid !== accountBook.uid) {
			return { code : 1002, msg : '权限不足，不允许修改非自身创建账本' };
		}
		
		const paramUtil = vk.require("service/client/accountbook/util/paramUtil");
		accountBook = await paramUtil.dealUpdateParam(accountBook);
		
		// 开启事务
		const transaction = await vk.baseDao.startTransaction();
		try {
			// 更新账本
			const row = await vk.daoCenter.accountBookDao.updateById({
				db: transaction,
				id: accountBook._id, 
				dataJson: {
					accountBookName,accountType,remarks,revision:accountBook.accountBook,lastUpdateTime:accountBook.lastUpdateTime
				}
			});
			if (row == null || row == 0) {
				throw new Error("更新账本失败");
			}
			// 提交事务
			await transaction.commit();
		} catch (err) {
			// 事务回滚
			await vk.baseDao.rollbackTransaction({db: transaction,err});
			console.error(`transaction error`, err)
		    return {
		      code: -1,
		      msg: "数据库写入异常,事务已回滚",
		      err: {
		        message: err.message,
		        stack: err.stack
		      },
			}
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
